<?php
/**
 * Created by PhpStorm.
 * User: root
 * Date: 11/13/18
 * Time: 3:51 PM
 */

namespace caroltc\jenkinsapp\library;


use caroltc\jenkinsapp\util\Helper;

class DbHandler
{
    private $LibPDO = null;

    public function __construct()
    {
        $database_config = Facade::config('database');
        $this->LibPDO = new LibPDO($database_config);
    }


    /**
     * @param $user_id
     * @return array
     */
    public function getJenkinsConfigList($user_id)
    {
        $data = $this->LibPDO->getAll("select * from user_jenkins_config where user_id = {$user_id} and status='NORMAL'");
        if (empty($data)) {
            return [];
        }
        return array_map(function($item) use ($user_id){
            $item['jenkins_username'] = Helper::unlock($item['jenkins_username'], $user_id);
            $item['jenkins_password'] = Helper::unlock($item['jenkins_password'], $user_id);
            $item['jenkins_api_token'] = Helper::unlock($item['jenkins_api_token'], $user_id);
            return $item;
        }, $data);
    }

    /**
     * @param $user_id
     * @param $jenkins_config_id
     * @return bool|array
     */
    public function getJenkinsConfigByUserIdAndConfigId($user_id, $jenkins_config_id)
    {
        $data = $this->LibPDO->getRow("select * from user_jenkins_config where user_id = {$user_id} and jenkins_config_id = {$jenkins_config_id} and status='NORMAL'");
        if (empty($data)) {
            return [];
        }
        $data['jenkins_url'] = urldecode($data['jenkins_url']);
        $data['jenkins_username'] = Helper::unlock($data['jenkins_username'], $user_id);
        $data['jenkins_password'] = Helper::unlock($data['jenkins_password'], $user_id);
        $data['jenkins_api_token'] = Helper::unlock($data['jenkins_api_token'], $user_id);
        return $data;
    }

    /**
     * @param $jenkins_config_id
     * @param $user_id
     * @param $data
     * @return bool
     */
    public function editJenkinsConfig($jenkins_config_id, $user_id, $data)
    {
        $can_edit_data = ['jenkins_name', 'jenkins_version', 'jenkins_url', 'jenkins_username', 'jenkins_password', 'jenkins_api_token'];
        foreach ($data as $key => $value) {
            if (!in_array($key, $can_edit_data)) {
                unset($data[$key]);
                continue;
            }
        }
        $data['jenkins_username'] = Helper::lock($data['jenkins_username'], $user_id);
        $data['jenkins_password'] = Helper::lock($data['jenkins_password'], $user_id);
        $data['jenkins_api_token'] = Helper::lock($data['jenkins_api_token'], $user_id);
        $data['update_time'] = date('Y-m-d H:i:s');
        return $this->LibPDO->update('user_jenkins_config', "jenkins_config_id={$jenkins_config_id} AND user_id={$user_id}", $data);
    }

    /**
     * @param $user_id
     * @param $data
     * @return bool|string
     */
    public function addJenkinsConfig($user_id, $data)
    {
        $can_add_data = ['jenkins_name', 'jenkins_version', 'jenkins_url', 'jenkins_username', 'jenkins_password', 'jenkins_api_token'];
        foreach ($data as $key => $value) {
            if (!in_array($key, $can_add_data)) {
                unset($data[$key]);
                continue;
            }
        }
        $data['jenkins_username'] = Helper::lock($data['jenkins_username'], $user_id);
        $data['jenkins_password'] = Helper::lock($data['jenkins_password'], $user_id);
        $data['jenkins_api_token'] = Helper::lock($data['jenkins_api_token'], $user_id);
        $now_time = date('Y-m-d H:i:s');
        $data['user_id'] = $user_id;
        $data['status'] = 'NORMAL';
        $data['create_time'] = $now_time;
        $data['update_time'] = $now_time;
        return $this->LibPDO->save('user_jenkins_config', $data);
    }

    /**
     * @param $jenkins_config_id
     * @return bool
     */
    public function deleteJenkinsConfig($jenkins_config_id, $user_id)
    {
        $data['update_time'] = date('Y-m-d H:i:s');
        $data['status'] = 'DELETED';
        return $this->LibPDO->update('user_jenkins_config', "jenkins_config_id={$jenkins_config_id} AND user_id={$user_id} AND status='NORMAL'", $data);
    }

    /**
     * @param $data
     * @return bool|string
     */
    public function saveUser($data)
    {
        $can_add_data = ['username', 'name', 'password'];
        foreach ($data as $key => $value) {
            if (!in_array($key, $can_add_data)) {
                unset($data[$key]);
                continue;
            }
        }
        $data['password'] = $this->makePassword($data['password']);
        $now_time = date('Y-m-d H:i:s');
        $data['status'] = 'NORMAL';
        $data['create_time'] = $now_time;
        $data['update_time'] = $now_time;
        return $this->LibPDO->save('user', $data);
    }

    /**
     * @param $user_id
     * @param $data
     * @return bool
     */
    public function update($user_id, $data)
    {
        if (isset($data['password'])) $data['password'] = $this->makePassword($data['password']);
        $data['update_time'] = date('Y-m-d H:i:s');
        return $this->LibPDO->update('user', "user_id={$user_id}", $data);
    }

    /**
     * @param $username
     * @param $password
     * @return false|mixed
     */
    public function getUserByPassword($username, $password)
    {
        $password = $this->makePassword($password);
        return $this->LibPDO->getRow("select * from user where username='{$username}' and password = '{$password}'");
    }

    /**
     * @param $username
     * @return false|mixed
     */
    public function getUserByUsername($username)
    {
        return $this->LibPDO->getRow("select * from user where username='{$username}'");
    }

    /**
     * @return array
     * @throws \Exception
     */
    public function getAllUser()
    {
        return $this->LibPDO->getAll("select user_id,name,username,status from user");
    }

    /**
     * @param $user_id
     * @return false|int
     */
    public function deleteUser($user_id)
    {
        return $this->LibPDO->update('user', 'user_id = ' . $user_id, ['status' => 'DISABLED']);
    }

    /**
     * generate password
     * @param $password
     * @return string
     */
    public function makePassword($password)
    {
        return md5(md5($password) . '1o0_skdj');
    }

    /**
     * @param $user_id
     * @return bool
     */
    public function getUserByUserId($user_id)
    {
        return $this->LibPDO->getRow("select * from user where user_id='{$user_id}'");
    }

    /**
     * @param $data
     * @return bool|string
     */
    public function createSession($data)
    {
        $now_time = date('Y-m-d H:i:s');
        $data['create_time'] = $now_time;
        return $this->LibPDO->save('user_session', $data);
    }

    /**
     * @param $token
     * @return bool
     */
    public function getSessionByToken($token)
    {
        return $this->LibPDO->getRow("select * from user_session where token='{$token}'");
    }
}